package com.ocom.exposeapi.controller;

import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2023/4/13
 **/
@RestController
public class TestController {

	@Autowired
	private HttpServletRequest request;

	@GetMapping("/ocom/test/header")
	public Result getHeader(){
		return ResultUtil.success(getHeadersInfo());
	}

	@GetMapping("/ocom/test/ip")
	public Result getAddr(){

		return ResultUtil.success(getRemoteAddr());
	}

	//get request headers
	private Map<String, String> getHeadersInfo() {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String key = (String) headerNames.nextElement();
			String value = request.getHeader(key);
			map.put(key, value);
		}
		return map;
	}


	public  Map<String, String> getRemoteAddr() {

		String ip = request.getHeader("X-Forwarded-For");
		Map<String, String> map = new HashMap<String, String>();

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
			map.put("Proxy-Client-IP", ip);
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

			ip = request.getHeader("WL-Proxy-Client-IP");
			map.put("WL-Proxy-Client-IP", ip);
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

			ip = request.getHeader("HTTP_CLIENT_IP");
			map.put("HTTP_CLIENT_IP", ip);
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			map.put("HTTP_X_FORWARDED_FOR", ip);

		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

			ip = request.getRemoteAddr();
			map.put("unknown", ip);

		}

		return map;

	}

}
